﻿using AdminBase.Common.Helpers;
using AdminBase.Interface;
using AdminBase.Model;
using AdminBase.Model.Entitys;
using AutoMapper;
using SqlSugar;

namespace AdminBase.Service
{
    /// <summary>
    /// 部门业务实现类
    /// </summary>
    public class DepartmentsService : IDepartmentsService
    {
        private readonly IMapper _mapper;
        private ISqlSugarClient _db { get; set; }

        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="db"></param>
        public DepartmentsService(IMapper mapper, ISqlSugarClient db)
        {
            _mapper = mapper;
            _db = db;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public bool Add(Departments entity)
        {
            entity = EntityHelper.SetAddValues(entity);
            return _db.Insertable(entity).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Edit(Departments entity)
        {
            var oEntity = _db.Queryable<Departments>().First(p => p.ID == entity.ID);
            oEntity = _mapper.Map(entity, oEntity);
            oEntity = EntityHelper.SetEditValues(oEntity);
            return _db.Updateable(oEntity).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Del(long id)
        {
            List<long> ids = new List<long>() { id };
            return DeletePermissionAndChildren(ids);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool BatchDel(List<long> idList)
        {
            if (idList.Any())
            {
                return DeletePermissionAndChildren(idList);
            }
            return false;
        }

        /// <summary>
        /// 删除及其子级
        /// </summary>
        /// <param name="pids">ID</param>
        private bool DeletePermissionAndChildren(List<long> pids)
        {
            List<long> ids = new List<long>();
            GetChildrenIDs(pids, ref ids);
            return _db.Deleteable<Departments>().In(ids).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 根据ID获取子级ID列表
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        private void GetChildrenIDs(List<long> pids, ref List<long> ids)
        {
            ids.AddRange(pids);
            // 获取所有子级ID
            var childIds = _db.Queryable<Departments>()
                               .Where(p => p.ParentID != null && pids.Contains(p.ParentID.Value))
                               .Select(p => p.ID)
                               .ToList();
            if (childIds.Any())
            {
                // 递归获取子级
                GetChildrenIDs(childIds, ref ids);
            }
        }

        /// <summary>
        /// 根据ID获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DepartmentsDto GetById(long id)
        {
            var info = _db.Queryable<Departments>().First(p => p.ID == id);
            return _mapper.Map<DepartmentsDto>(info);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="queryParam">查询参数</param>
        /// <returns></returns>
        public PageInfo GetDepartments(DepartmentsQueryParam queryParam)
        {
            PageInfo pageInfo = new PageInfo();
            var exp = _db.Queryable<Departments>();
            // 关键字
            if (!string.IsNullOrWhiteSpace(queryParam.KeyWord))
            {
                exp = exp.Where(p =>
                p.Name.Contains(queryParam.KeyWord)
                || (p.Description != null && p.Description.Contains(queryParam.KeyWord)));
            }

            var list = _mapper.Map<List<DepartmentsDto>>(
                exp.OrderBy(p => p.Sort == null ? int.MaxValue : p.Sort)
                .ToList());

            // 从一级开始往下找子级
            List<DepartmentsDto> level1list = list.Where(p => p.ParentID == 0 || p.ParentID == null).ToList();
            //通过递归获取子级
            GetChildren(list, level1list);
            var resultList = level1list.Distinct(new DisComparer<DepartmentsDto>("Name")).ToList();

            // 排序、分页
            pageInfo.Data = resultList;
            pageInfo.Count = list.Count();

            return pageInfo;
        }

        /// <summary>
        /// 递归获取子
        /// </summary>
        /// <param name="all"></param>
        /// <param name="res"></param>
        private static void GetChildren(List<DepartmentsDto> all, List<DepartmentsDto> res)
        {
            if (res != null && res.Count > 0)
            {
                res.ForEach(item =>
                {
                    var child = all.Where(p => p.ParentID == item.ID)
                    .OrderBy(p => p.Sort == null ? int.MaxValue : p.Sort)
                    .ToList();
                    if (child != null && child.Count > 0)
                    {
                        item.Children = child;
                        GetChildren(all, child);
                    }
                });
            }
        }

        /// <summary>
        /// 获取树形数据
        /// </summary>
        /// <returns></returns>
        public List<TreeDto> GetTreeData()
        {
            var list = _db.Queryable<Departments>()
                .OrderBy(p => p.Sort)
                .Select(u => new TreeBase
                {
                    ID = u.ID,
                    Name = u.Name,
                    ParentID = u.ParentID,
                }).ToList();
            return TreeDataHelper.GetTreeData(list);
        }
    }
}
